/**
 * 
 */
package com.munoor.dalai.server.servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;

import com.munoor.dalai.server.model.EMFService;
import com.munoor.dalai.server.model.User;
import com.munoor.dalai.server.utils.Hash;
import com.munoor.dalai.server.utils.HashHolder;

/**
 * @author Osho
 * 
 */
public final class RegisterServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		BufferedReader reader = request.getReader();
		ObjectMapper mapper = new ObjectMapper();
		User user = null;
		EntityManager em = EMFService.get().createEntityManager();
		int existingCount = -1;
		try {
			user = mapper.readValue(reader, User.class);
			existingCount = ((Integer) em.createNamedQuery("Users.getSingleEmailCount").setParameter("email", user.getEmail()).getSingleResult()).intValue();
			existingCount = existingCount + ((Integer) em.createNamedQuery("Users.getSingleUsernameCount").setParameter("username", user.getUsername()).getSingleResult()).intValue();
		} catch (Exception e) {
			// in case malformed JSON posted and can not be unmasshalled by Jackson
			// or general DB error
			// e.printStackTrace();
		}
		reader.close();
		//precheck the unmarshalled JSON is sensible
		if ( (user == null) ||  (user.getUsername() == null || user.getUsername().length() < 6) || (user.getEmail() == null || user.getEmail().length() < 6) || (user.getPassword() == null || user.getPassword().length() < 6)){
			//invalid JSON. Was not from our client or was not properply transmitted/unmarshalled
			existingCount = -1;
		}
		
		if (existingCount == 0) {
			HashHolder hashData = Hash.getMD5Hash(user.getPassword());
			user.setPassword(hashData.getHash()); // change plain text PW to hash
			user.setWelcome(hashData.getSalt());
			user.setvCode(Hash.getMD5Hash(user.getEmail()).getHash());	
			user.setUserType((short)4);
			em.persist(user);
			em.close();
			user.setPassword("");
			user.setWelcome(0);
			HttpSession session = request.getSession();
			session.setAttribute("userid", user);
			response.setContentType("application/json");
			response.setStatus(HttpServletResponse.SC_OK);
			PrintWriter out = response.getWriter();
			//{"userId":7,"userType":1}
			out.println("{\"userId\":"  + user.getUserId() + ", \"userType\":" + user.getUserType() + "}");
			out.close();
			//mapper.writeValue(response.getWriter(), user);
		} else {
			// credentials in use or DB error ( i.e. existingCount != 0) or JAXBJSON parse failed
			response.setStatus(HttpServletResponse.SC_FORBIDDEN);
			em.close();
		}
		

	}
}
